package com.lagou.rocket.service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lagou.rocket.entity.Order;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
@Component
public class RocketMQConsumer2 {

    @Resource
    private WarehouseService warehouseService;
    @Autowired
    private OrderService orderService;

    @Value("${rocketmq.name-server}")
    private String namesrvAddr;

    @Autowired
    private ObjectMapper objectMapper;

    @SneakyThrows
    @PostConstruct
    public void init(){
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("mq-order-consumer-group");
        consumer.setNamesrvAddr(namesrvAddr);
        consumer.subscribe("mq-order-lagouphone", "*");
        consumer.setMessageListener((MessageListenerOrderly) (msgs, context) -> {
            for (MessageExt msg : msgs) {
                try {
                    String obj = new String(msg.getBody(), "utf-8");
                    Order order = objectMapper.readValue(obj, Order.class);
                    onMessage(order);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return ConsumeOrderlyStatus.SUCCESS;
        });
        consumer.start();
    }

    public void onMessage(Order order) {
        boolean hasStock = warehouseService.hasStock(order.getName(), order.getNum());
        if (!hasStock) {
            log.info("库存不足");
            return;
        }
        log.info("扣减库存");
        warehouseService.stock(order.getName(), -order.getNum());

        log.info("创建订单,id:"+order.getId());
        boolean flg = orderService.createOrder(order);
        if (flg){
            warehouseService.realstock(order.getName(),-order.getNum());
        }
    }


}

